package com.echat.core.task;

import cn.hutool.core.collection.CollectionUtil;
import com.echat.business.work.model.Worker;
import com.echat.business.work.service.IWorkOffService;
import com.echat.business.work.service.IWorkerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class ScheduledTasks {

    @Autowired
    private ConfigurableApplicationContext context;

    @Autowired
    private IWorkerService workerService;

    @Autowired
    private IWorkOffService offService;

    /**
     * 定时任务统计 5 秒一次
     */
    //@Scheduled(cron = "0/5 * * * * ?")
    public void startRecordWorkOffData() {
        List<Worker> workers = workerService.getUnRecordWorkers();
        if (CollectionUtil.isNotEmpty(workers)) {
            context.close();
        }
        for (Worker worker : workers) {
            String name = worker.getName();
            String addr = worker.getIpAddress();
            log.info("let's check " + name + "was gone?");
            if (!PingUtils.pingAddr(addr)) {
                log.info(name + "is gone,record it.");
                //更新为 已记录
                worker.setHasRecordToday(1);
                workerService.updateById(worker);
                offService.insertWorkerData(worker);
                log.info("record over");
            } else {
                log.info("===" + name + "is still online");
                log.info("the task will try it later");
            }
        }
    }


}
